package auctionhaus

import grails.converters.JSON


class MailJob {

    def emailService
    def listingCompletionService

    static triggers = {
        simple name: 'mySimpleTrigger', startDelay: 5000, repeatInterval: 20000
    }

    def group = "MyGroup"

    def sendWinnerEmail(Listing listing)
    {
        String messageBody = "";
        messageBody += "<br/> Greetings " + listing.winner.email + "!"
        messageBody += "<br/>Congratulations!  You have won a bid on Auction Haus!"
        messageBody += "<br/> Listing ID: " + listing.id
        messageBody += "<br/> Listing Name: " + listing.name
        if(listing.description)
        {
            messageBody += "<br/> Listing Description: " + listing.description
        }
        messageBody += "<br/> Ended at: " + listing.endDateTime.toString()
        messageBody += "<br/> Your winning bid is \$" + listing.bids.last().amount
        messageBody += "<br/> You may view the listing at <a href=\"http://localhost:8080/AuctionHaus/listing/show/"
        messageBody += listing.id
        messageBody += "\">Auction Haus</a>"
        messageBody += "<br/>Thanks for your business!"
        messageBody += "<br/>The Auction Haus Robots"

        Email winnerEmail = new Email(to: listing.winner.email,
                                      fromField: "auctionhowse@gmail.com",
                                      body: messageBody.toString(),
                                      subject: "You have the winning bid!",
                                      model: "[greeting: messageBody]",
                                      view: "/email/email",
                                      listingId: listing.id)

        //C-1 Create the JSON and send it to the Email Service
        emailService.sendEmail((winnerEmail as JSON).toString())
    }

    def sendSellerEmail(Listing listing, Boolean hasWinner)
    {
        String messageBody = ""
        messageBody += "<br/> Greetings " + listing.seller.email + "!"
        messageBody += "<br/>Your listing on Auction Haus has completed."
        messageBody += "<br/> Listing ID: " + listing.id
        messageBody += "<br/> Listing Name: " + listing.name
        messageBody += "<br/> You may view the listing at <a href=\"http://localhost:8080/AuctionHaus/listing/show/"
        messageBody += listing.id
        messageBody += "\">Auction Haus</a>"
        if(listing.description)
        {
            messageBody += "<br/> Listing Description: " + listing.description
        }
        messageBody += "<br/> Ended at: " + listing.endDateTime.toString()
        if(hasWinner)
        {
            messageBody += "<br/> The winning bid was placed by " + listing.winner.email +
                           "<br /> The winning bid is \$" + listing.getBids().last().amount
        }
        else
        {
            messageBody += "<br/> Unforunately, your listing did not generate any bid! Better luck next time!"
        }
        messageBody += "<br />Thanks for your business!"
        messageBody += "<br />The Auction Haus Robots"

        Email sellerEmail = new Email(to: listing.seller.email,
                fromField: "auctionhowse@gmail.com",
                body: messageBody.toString(),
                subject: "Your Listing has completed",
                model: "[greeting: messageBody]",
                view: "/email/email",
                listingId: listing.id)

        //C-1 Create the JSON and send it to the Email Service
        emailService.sendEmail((sellerEmail as JSON).toString())
    }

    def execute(){
        try{

            //C-1: When a listing completes, post a message to a JMS Queue representing sending the completed listing as JSON
            List list = Listing.findAllByEndDateTimeLessThanAndCompletedNotEqual(new Date(), true)
          
            list.each {

                logListing(it)

                //mark as completed
                it.completed = true
                it.save(flush: true)

                //Find the winner
                Boolean hasWinner = false
                if(!it.bids.empty)
                {
                    Bid winningBid = it.bids.last()
                    it.winner = winningBid.getBidder()
                    sendWinnerEmail(it)
                    hasWinner = true
                }

                sendSellerEmail(it, hasWinner)
            }
        } catch (Exception e) {
            log.error("${e}", e)
            print e
            return
        }
        print "Job run!"
    }

    def logListing(Listing listing){
        print "here is a listing:"
        print "listing: " + listing.id
        print "name: " + listing.name
        print "seller" + listing.seller
        print "completed " + listing.completed
        print "listing done"
    }

}
